import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/dialog/permission_dialog.dart';

/// @description:
/// @author tangzhentao
/// @created at 21:51 2024/11/24


/// 通用appbar
AppBar xfgAppbar({
  Widget? leading,
  GestureTapCallback? onBack,
  Color? backgroundColor,
  Widget? titleWidget,
  String? title,
  Widget? centerWidget,
  Color? titleColor,
  Widget? flexibleSpace,
  List<Widget>? actions,
  PreferredSizeWidget? bottom,
  SystemUiOverlayStyle systemOverlayStyle = SystemUiOverlayStyle.dark,
}) {
  final isDark = systemOverlayStyle == SystemUiOverlayStyle.dark;
  return AppBar(
    systemOverlayStyle: systemOverlayStyle,
    leadingWidth: XfgSize().size48,
    leading: InkWell(
      onTap: () {
        FocusManager.instance.primaryFocus?.unfocus();
        if (onBack != null) {
          onBack.call();
        } else {
          XfgNav.pop();
        }
      },
      child: Container(
        height: kToolbarHeight,
        alignment: Alignment.center,
        child: Icon(Icons.arrow_back_ios_new_rounded, size: XfgSize().size16, color: isDark ? XfgColor.text1D:XfgColor.white),
      ),
    ),
    title: centerWidget ?? (titleWidget ??(title != null ? Text(title, style: TextStyle(fontSize: XfgSize().text18, fontWeight: FontWeight.w500, color: isDark ? XfgColor.text1:XfgColor.white)):null)),
    actions: actions?..add(SizedBox(width: (kToolbarHeight - XfgSize().size10) / 2)),
    backgroundColor: backgroundColor?? XfgColor.white,
    surfaceTintColor: XfgColor.transparent,
    flexibleSpace: flexibleSpace,
    bottom: bottom,
    centerTitle: true,
    elevation: 0,
  );
}

/// 登录的输入框装饰器
final loginTextFieldDecoration = BoxDecoration(border: Border.all(color: XfgColor.colorE, width: XfgSize().size0_5), borderRadius: BorderRadius.circular(XfgSize().size25));

/// 通用的白色背景圆角6dp的装饰器
final white6Decoration = BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.circular(XfgSize().size6));

/// 通用的白色背景圆角10dp的装饰器
final white10Decoration = BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.circular(XfgSize().size10));

/// 底部描边的装饰器
final bottomBorderDecoration = BoxDecoration(border: Border(bottom: BorderSide(color: XfgColor.colorE, width: XfgSize().size0_5)));

/// 所有方向描边
final allBorder = Border.all(width: XfgSize().size0_5, color: XfgColor.colorE);

/// 单边描边
final singleBorderSide = BorderSide(width: XfgSize().size0_5, color: XfgColor.colorE);

/// 分割线
final strokeHeightContainer = Container(height: XfgSize().size0_5, color: XfgColor.colorE);

/// 分割线
final strokeWidthContainer = Container(width: XfgSize().size0_5, color: XfgColor.colorE);

/// 底部导航栏高度
final bottomNavigatorWidget = SizedBox(height: XfgSize().bottomBarHeight == 0 ? XfgSize().size1:XfgSize().bottomBarHeight);

/// TextButton样式
ButtonStyle xfgButtonStyle(Size size, {double? radius, Color color = XfgColor.theme, BorderSide side = BorderSide.none}) => ButtonStyle(
    visualDensity: VisualDensity.compact,
    backgroundColor: WidgetStateProperty.resolveWith((states) {
      if (states.contains(WidgetState.disabled)) {
        return color.withValues(alpha: 0.6);
      }
      return color;
    }),
    shape: WidgetStatePropertyAll(RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(radius ?? XfgSize().size6),
      side: side
    )),
    fixedSize: WidgetStatePropertyAll(size)
);

/// 测量文字宽度
Size boundingTextSize(String text, {TextStyle style = const TextStyle(),int maxLines = 2^31, double maxWidth = double.infinity}) {
  if (text.isEmpty) {
    return Size.zero;
  }

  final TextPainter textPainter = TextPainter(
      textDirection: TextDirection.ltr,
      text: TextSpan(text: text, style: style), maxLines: maxLines)
    ..layout(maxWidth: maxWidth);
  return textPainter.size;
}

/// radio 图标
Widget xfgRadio({required bool value, double? size}) => Icon(value ? Icons.radio_button_on:Icons.radio_button_off, size: size?? XfgSize().size16, color: value ? XfgColor.radioSelected:XfgColor.colorB5);

/// 选择图片 拍照或相册
Future<List<File>?> pickPhoto({max = 5}) async {
  final result = await _showPickPhotoTypeDialog(XfgNav.currentContext);
  if (result != null) {
    if (result) {
      /// 相册
      final permissionResult = await showRequestPermissionDialog(permissions: [Platform.isAndroid ? Permission.storage:Permission.photos]);
      if (permissionResult) {
        final assets = await AssetPicker.pickAssets(XfgNav.currentContext, pickerConfig: AssetPickerConfig(maxAssets: max));
        if (assets?.isNotEmpty == true) {
          final files = <File>[];
          await Future.forEach(assets!, (asset) async {
            final file = await asset.file;
            if ((await file?.exists())?? false) {
              files.add(file!);
            }
          });
          return files;
        }
        '未选择图片'.toast();
        return null;
      }
    } else {
      /// 拍照
      final permissionResult = await showRequestPermissionDialog(permissions: [Permission.camera]);
      if (permissionResult) {
        final asset = await CameraPicker.pickFromCamera(XfgNav.currentContext, pickerConfig: const CameraPickerConfig());
        final file = await asset?.file;
        if ((await file?.exists())?? false) {
          return [file!];
        } else {
          '未拍照'.toast();
          return null;
        }
      }
    }
  } else {
    '未选择图片/未拍照'.toast();
    return null;
  }
  '未选择图片/未拍照'.toast();
  return null;
}

/// 选择图片方式弹窗
Future<bool?> _showPickPhotoTypeDialog(BuildContext context) async {
  return await showCupertinoModalPopup<bool>(context: context, builder: (_) => CupertinoActionSheet(
    actions: [
      CupertinoActionSheetAction(
        onPressed: () => XfgNav.pop(true),
        child: const Text('相册', style: TextStyle(color: XfgColor.cupertinoActionSure)),
      ),
      CupertinoActionSheetAction(
        onPressed: () => XfgNav.pop(false),
        child: const Text('拍照', style: TextStyle(color: XfgColor.cupertinoActionSure)),
      ),
    ],
    cancelButton: const CupertinoActionSheetAction(
      isDefaultAction: true,
      onPressed: XfgNav.pop,
      child: Text('取消', style: TextStyle(color: XfgColor.text3)),
    ),
  ));
}

/// 显示信息
void xfgShowSnackBar(BuildContext context, String title, String value) {
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: XfgText('$title"$value"已复制到剪切板', color: XfgColor.white, fontSize: XfgSize().text14, bold: FontWeight.bold),
      backgroundColor: XfgColor.theme, showCloseIcon: true,
    ),
  );
}